import { reqCartList, reqdeleteCart, reqUpdateCheckedByid } from '@/api'

const state = {
  cartList: []
}
const mutations = {
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const actions = {
  // 获取购物车列表数据
  async getCartList({ commit }) {
    let result = await reqCartList()
    if (result.code == 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  // 删除购物车
  async deleteCartlistBySkuId({ commit }, skuid) {
    let result = await reqdeleteCart(skuid)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 切换商品选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedByid(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 删除购物车选中产品
  deletAllCheckdCart({ getters, dispatch }) {
    // context ：小仓库 getters.cartList.cartInfoList
    let PromiseAll = []
    // 获取购物车全部产品
    getters.cartList.cartInfoList.forEach(element => {
      let promise = element.isChecked == 1 ? dispatch('deleteCartlistBySkuId', element.skuId) : ''
      // 将每一次得返回得promise添加到数组中
      PromiseAll.push(promise)
    });
    return Promise.all(PromiseAll)
  },
  // 更新购物测选中 状态
  updateAllCartIsChecked({ getters, dispatch },isChecked ) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(element => {
       let promise =  dispatch('updateCheckedById', {
        skuId: element.skuId,
        isChecked
      })
      PromiseAll.push(promise)
    });
    return Promise.all(PromiseAll)
  }

}

// 简化数据
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  }
}

export default {
  state,
  mutations,
  actions,
  getters,
}